﻿angular.module('app')
    .directive("topicList", [function () {
        return {
            restrict: 'E',
            replace: true,
            templateUrl: 'scripts/app/views/topic/index.html'
        };
    }])
    .directive("topicBox", ['TopicSrv', '$timeout', 'globalConfig', 'helperSrv', '$document', '$window', '$interval', 'WorkContextSrv', '$rootScope', function (topicSrv, $timeout, globalConfig, helperSrv, $document, $window, $interval, workContextSrv, $rootScope) {
        return {
            scope: {
                topic: '=',
                showdate: '&'
            },
            replace: true,
            restrict: 'E',
            templateUrl: 'scripts/app/views/topic/box.html',
            link: function (scope, element) {
                var postUrl = 'api/topics';
                var currentUser = workContextSrv.getCurrentUser();
                var username = currentUser.userName;
                var formUpload;

                scope.topic.showDateDivider = scope.showdate({ myDate: scope.topic.message.whenDay });

                scope.allowedExtension = globalConfig.allowedExtension;
                /* Start Setup File Upload */
                //set max files
                scope.maximumFiles = globalConfig.maxFiles;
                //set file size
                var fileSize = globalConfig.fileSize;
                var filesList = [];

                //scroll to bottom
                var elem = $(element).find("#chat-body");
                if (typeof elem[0] != 'undefined') {
                    var height = elem[0].scrollHeight;
                    elem.scrollTop(height);
                }

                //get filename from path
                var getFileNameFromPath = function (fullPath) {
                    var index = fullPath.lastIndexOf("\\") + 1;
                    if (index === 0) {
                        index = fullPath.lastIndexOf("/") + 1;
                    }
                    var filename = fullPath.substr(index);

                    return filename;
                };

                //validate file function
                function validateFile(fileName, filesi) {
                    var validFile = true;
                    //validate extension
                    if (!(globalConfig.regexAllowedExtension).test(fileName)) {
                        alert('Only accepted file types: ' + globalConfig.allowedExtension);
                        validFile = false;
                    }
                    //validate fileSize (not support in <= IE 9)
                    if (filesi > 0 && filesi > fileSize) { // 2mb
                        alert('Please upload a smaller file, max size is 0.5 MB (512kb)');
                        validFile = false;
                    }
                    //validate maxFiles
                    if (filesList.length >= 3) {
                        alert('Max files is reached');
                        validFile = false;

                    }
                    return validFile;
                }

                function changeFileUploadControl(e) {
                    if (typeof jQuery(e) != 'undefined') {
                        jQuery(e).removeClass("active-file");
                        jQuery(e).addClass("has-file");
                        if (typeof jQuery(e).next() != 'undefined') {
                            if (!jQuery(e).next().hasClass("has-file")) {
                                jQuery(e).next().addClass("active-file");
                            } else {
                                changeFileUploadControl(jQuery(e).next());
                            }
                        }
                    }
                }

                //file change function
                function fileChange() {
                    var fileName = getFileNameFromPath(jQuery(this).val());
                    jQuery(this).removeClass("file-error");
                    if (!validateFile(fileName, 0)) {
                        jQuery(this).addClass("file-error");
                    } else {
                        scope.$broadcast('fileadded', { file: fileName });
                        changeFileUploadControl(jQuery(this));
                    }
                }

                //get id
                var fileUploadId = new Date().getTime();

                function createUploadControl() {
                    //clear old file upload control
                    jQuery(element).find(".btnupload").html('');
                    //append new file upload control
                    for (var i = 0; i < scope.maximumFiles; i++) {
                        jQuery("<input type='file' id='file-" + i + "' class='ie-file " + (i == 0 ? "active-file" : "") + "' name='files[]'>").appendTo(jQuery(element).find(".btnupload")).bind("change", fileChange);
                    }
                }
                
                //Handle 'fileadded' event
                scope.$on('fileadded', function (e, parameters) {
                    if (helperSrv.isIe() === 9) {
                        scope.$apply(function () {
                            scope.reply.attachments.push({ name: parameters.file });
                        });
                    }
                    else {
                        scope.reply.attachments.push(parameters.file);
                    }
                });

                //remove attactment
                scope.deleteCurrentAttachment = function (idx, event) {
                    event.preventDefault();
                    //remove file from reply scope
                    scope.reply.attachments = scope.reply.attachments.filter(
                    function (val) {
                        return val !== this.file;
                    }, this);

                    //remove file from fileList array
                    filesList = filesList.filter(
                    function (val) {
                        return val !== this.file;
                    },
                    this);

                    if (helperSrv.isIe() === 9) {
                        var elementId = jQuery(element).find(".btnupload").find("input[type=file]").eq(idx).attr("id");
                        jQuery(element).find(".btnupload").find("input[type=file]").eq(idx).remove();
                        jQuery("<input type='file' id='" + elementId + "' class='ie-file active-file' name='files[]'>").appendTo(jQuery(element).find(".btnupload")).bind("change", fileChange);
                    }
                };
                /* End Setup File Upload */

                /* Start Setup submit reply */
                var maxFlood = 5;
                var isOkToPostReply = false;
                var floodTime = null;
                scope.replyFlood = 5;
                scope.reply = { body: '', entertosend: false, attachments: [] };
                scope.showError = false;
                scope.floodError = false;
                scope.isPosting = false;
                scope.hasErrorWhilePosting = false;
                scope.errorMessage = '';

                scope.topicReply = {
                    templateUrl: ''
                };

                var maxLength = 500;

                //replies
                scope.topicReplies = {
                    recentReplies: [],
                    olderReplies: [],
                    loadingReplies: false,
                    loadingOlderReplies: false,
                    showOlderReplies: false,
                    hasOlderReplies: false,
                    hasExpanded:false
                };

                function validate(input, type) {
                    if (type === 'required') {
                        return (scope.showError && (typeof input === 'undefined' || input === ''));
                    }
                    else if (type === 'maxlength') {
                        if (typeof input !== 'undefined') {
                            var ipt = input.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, "<br/>");
                            return ipt.length > maxLength-10;
                        }
                    }
                    return false;
                }

                //validate input
                scope.validate = function (field, type) {
                    return validate(scope.reply.body, type);
                };
                
                //submit reply
                scope.submitReply = function (reply, topic, frombutton) {
                    if (scope.isPosting) {
                        return;
                    }

                    scope.hasErrorWhilePosting = false;
                    isOkToPostReply = false;

                    scope.showError = true;

                    //if the body is empty then show error
                    if ((validate(reply.body, 'required') || validate(reply.body, 'maxlength'))) {
                        return;
                    }

                    //if topic and reply is not undefined and null
                    if (typeof topic != 'undefined' && topic != null) {
                        //if body is empty
                        if (reply.body === '') {
                            return;
                        }
                        //hide error
                        scope.showError = false;

                        //if user click on button
                        if (frombutton) {
                            isOkToPostReply = true;
                        } else {
                            //if 'Enter to send' is true
                            var enterToSend = (typeof reply.entertosend != 'undefined' && reply.entertosend);
                            if (enterToSend) {
                                isOkToPostReply = true;
                            }
                        }
                        if (isOkToPostReply) {
                            scope.showError = false;
                            //Prenvent flood
                            //if counting
                            if (floodTime != null) {
                                scope.floodError = true;
                                return;
                            }
                            var to = topic.message.to;
                            scope.isPosting = true;
                            var message = scope.reply.body.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, "<br/>");
                            //Post to server
                            if ((helperSrv.isIe() === 9)) {
                                //create unique id
                                var frameId = "upload_frame_" + new Date().getTime();
                                //append iframe for post
                                jQuery(element).append('<iframe id="' + frameId + '" name="' + frameId + '" class="hidden"></iframe>');
                                //handle event when iframe loaded
                                jQuery('#' + frameId).on('load', function () {
                                    //parse result to json
                                    var resp = angular.fromJson(jQuery(this).contents().find('pre').html());
                                    //hide indicator
                                    scope.isPosting = false;
                                    //fire 'replyadded' event
                                    $timeout(function () {
                                        scope.$broadcast('replyadded', { data: resp });
                                    });
                                    //remove iframe
                                    jQuery(this).remove();
                                    createUploadControl();
                                });
                                //get form
                                var $form = jQuery(element).find("form");
                                //remove input file without selected file
                                $form.find(".btnupload input[type=file]").each(function () {
                                    if (!jQuery(this).hasClass("has-file")) {
                                        jQuery(this).remove();
                                    }
                                });
                                //append message input
                                jQuery(element).find("form").find("#replymessage").remove();
                                jQuery("<textarea id='replymessage' name='message' class='hidden'></textarea>").appendTo(jQuery(element).find("form")).val(message);
                                //add attribute to form
                                $form.attr('action', postUrl + '?tid=' + topic.topicId + '&from=' + username + '&to=' + to);
                                $form.attr('method', 'post');
                                $form.attr('enctype', 'multipart/form-data');
                                //change target to iframe and submit
                                $form.attr('target', frameId).submit();

                            } else {
                                topicSrv.addReply({tid: topic.topicId, from: username, to: to }, { message: message, filesList: filesList })
                                   .success(function (dt) {
                                       scope.isPosting = false;
                                       $timeout(function () {
                                           scope.$broadcast('replyadded', { data: dt });
                                       });
                                   });
                            }
                        }
                    } else {
                        //show error
                        scope.showError = true;
                    }
                };

                //load older replies
                scope.loadOlderMessages = function (tp) {
                    scope.topicReplies.loadingOlderReplies = true;
                    topicSrv.getTopicReplies(username, tp.topicId, 'Old')
                        .then(function () {
                            scope.topicReplies.loadingOlderReplies = false;
                            Array.prototype.push.apply(scope.topicReplies.olderReplies, topicSrv.replies.replies);
                            //scope.topicReplies.olderReplies = dt.replies;

                            scope.topicReplies.showOlderReplies = true;
                        },
                        function(error) {
                            // TODO: error 
                        }
                    );
                };

                //prevent new line when press enter
                scope.preventNewLine = function (reply, $event) {
                    if (reply.entertosend) {
                        $event.preventDefault();
                    }
                };

                //Handle 'replyadded' event
                scope.$on('replyadded', function (e, parameters) {
                    var resp = parameters.data;
                    if (resp.result) {
                        //get user image
                        var photoPath = currentUser.photoPath;

                        //remove queue files
                        jQuery(element).find(".files").empty();

                        //get attachments
                        var attachmentList = [];
                        if (resp.reply.attachments != null) {
                            for (var i = 0; i < resp.reply.attachments.length; i++) {
                                attachmentList.push({ fileName: resp.reply.attachments[i].fileName, oid: resp.reply.attachments[i].documentOid });
                            }
                        }

                        //remove file list
                        filesList = [];
                        //reset model
                        scope.$apply(function () {
                            //append reply to replies list
                            scope.topicReplies.recentReplies.push({ "status": "New", "imageUrl": photoPath, "from": username, "to": "", "when": "4/7/2014", "message": resp.reply.message, "attachments": attachmentList });
                            //reset model
                            scope.reply = { body: '', entertosend: scope.reply.entertosend, attachments: [] };
                        });

                        //scroll window to bottom
                        var elem = jQuery(element).find("#chat-body");
                        if (typeof elem[0] != 'undefined') {
                            var height = elem[0].scrollHeight;
                            elem.scrollTop(height);
                        }
                    } else {
                        //show error
                        scope.hasErrorWhilePosting = true;
                        scope.errorMessage = resp.errorMessage;
                    }

                    scope.isPosting = false;
                    //Re-counting
                    scope.replyFlood = maxFlood;
                    //create counting
                    floodTime = $interval(function () {
                        if (scope.replyFlood == 0) {
                            $interval.cancel(floodTime);
                            floodTime = null;
                            scope.floodError = false;
                        } else {
                            scope.replyFlood = scope.replyFlood - 1;
                        }
                    }, 1000);
                });
                /* End setup submit reply */

                //handle topic box collapse event
                scope.$on("topicBoxCollapsed", function (e, p) {
                    if (!p) {
                        scope.topicReply.templateUrl = '';
                    }
                    scope.topicReplies.hasExpanded = p;
                });

                //collapse if click outside topic box
                $document.bind('click', function (e) {
                    if (!angular.element(e.target).parents(".topic-message").length > 0 && !angular.element(e.target).parents(".topic-replies").length > 0 && !angular.element(e.target).hasClass('btnRemoveAttachment') && !angular.element(e.target).hasClass('topic-box-loading-replies') && !angular.element(e.target).hasClass('modal') && !angular.element(e.target).parents(".modal").length>0) {
                        scope.topicReply.templateUrl = '';
                        scope.$emit("topicBoxCollapsed", false);
                        angular.element(".topic-replies").removeClass("slidein");
                    }
                });
                
                //expand function
                scope.expandTopicBox = function ($event, tp) {
                    if (angular.element($event.target).hasClass('message-avatar') || angular.element($event.target).hasClass('message-username') || angular.element($event.target).hasClass('btnsavefile') || angular.element($event.target).hasClass('topic-box-loading-replies')) {
                        $event.preventDefault();
                        return;
                    }
                    if (angular.element(element).find(".topic-replies").hasClass("slidein")) {
                        scope.topicReply.templateUrl = '';
                        scope.$emit("topicBoxCollapsed", false);
                        angular.element(element).find(".topic-replies").removeClass("slidein");
                    } else {
                        //load Replies
                        scope.topicReplies.recentReplies = [];
                        scope.topicReplies.hasOlderReplies = false;

                        scope.topicReplies.loadingReplies = true;
                        topicSrv.getTopicReplies(username, tp.topicId, 'Recent')
                            .then(function () {
                                scope.topicReply.templateUrl = 'scripts/app/views/topic/box.reply.html';

                                Array.prototype.push.apply(scope.topicReplies.recentReplies, topicSrv.replies.replies);
                                //scope.topicReplies.recentReplies = dt.replies;

                                scope.topicReplies.loadingReplies = false;
                                scope.topicReplies.hasOlderReplies = topicSrv.replies.hasOldReplies;

                                setTimeout(function () {
                                    if (scope.topic.status !== 'Read') {
                                        topicSrv.removeCache();
                                    }
                                    scope.topic.status = 'Read';
                                    angular.element(element).find(".topic-replies").addClass("slidein");
                                    scope.$emit("topicBoxCollapsed", true);
                                }, 100);
                            },
                            function(error) {
                                // TODO: error;
                            }
                        );
                    }
                };

                scope.onTopicReplyLoad = function () {
                    setTimeout(function () {
                    //Check if browser support drag and drop file
                    if (helperSrv.isIe() === 9) {
                        //add class to html
                        jQuery("html").addClass("notsupportdragdrop");
                        createUploadControl();
                    } else {
                        //add dropzone
                        jQuery(element).find(".textarea-div").prepend("<div id='" + fileUploadId + "' class='dropzone'></div>");
                        jQuery(element).find(".btnupload").append("<input type='file' name='files[]' multiple>");

                        //file upload config
                        var config = {
                            dropZone: jQuery('#' + fileUploadId),
                            autoUpload: false
                        };

                        //setup file upload
                        $timeout(function () {
                            formUpload = jQuery(element).find(".btnupload input[type=file]").fileupload(config)
                                .bind('fileuploadadd', function (e, data) {
                                    // Turn the FileList object into an Array
                                    for (var i = 0; i < data.files.length; i++) {
                                        //if file is valiad
                                        if (validateFile(data.files[i].name, data.files[i].size)) {
                                            //fire 'fileadded' event
                                            scope.$broadcast('fileadded', { file: data.files[i] });
                                            filesList.push(data.files[i]);
                                        }
                                    }
                                })
                                .bind('fileuploaddone', function (e, data) {
                                    scope.$broadcast('replyadded', { data: data.jqXHR.responseJSON });
                                })
                                .bind('fileuploadprogressall', function () { });
                        }, 200);
                    }
                }, 500);
                };

                //view user info
                scope.viewUserInfo = function (userName) {
                    var params = { userName: userName, currentUserList: workContextSrv.getCurrentUser().following };
                    $rootScope.$broadcast("openPopupViewUserInfo", params);
                };
            }
        };
    }])
    .directive("createTopicBox", ['helperSrv', 'globalConfig', 'WorkContextSrv', 'TopicSrv', '$timeout', '$rootScope',
function (helperSrv, globalConfig, workContextSrv, topicSrv, $timeout, $rootScope) {
    return {
        replace: true,
        restrict: "E",
        templateUrl: 'scripts/app/views/topic/createTopicBox.html',
        link: function(scope, element) {
            var postUrl = 'api/topics';
            var fileSize = globalConfig.fileSize;
            var filesList = [];
            var formUpload;
            var currentUser = workContextSrv.getCurrentUser();
            var username = currentUser.userName;
            //Create newtopic object
            scope.newTopicMaxFiles = globalConfig.maxFiles;
            scope.newtopic = { /*title: '',*/ attachments: [], message: '', directTo: [] };
            scope.onSubmitting = false;
            scope.showError = false;
            scope.hasErrorWhilePosting = false;
            scope.errorMessage = '';
            
            scope.isDirectTo = false;

            //expand direct to
            scope.expandDirectTo = function ($event) {
                //console.log(scope.isDirectTo);
                if (!angular.element($event.target).is(":checked")) {
                    scope.newtopic.directTo = [];
                    angular.element("#directtoblock").slideUp();
                } else {
                    angular.element("#directtoblock").slideDown();
                }
                scope.isDirectTo = angular.element($event.target).is(":checked");
            };

            //get filename from path
            var getFileNameFromPath = function (fullPath) {
                var index = fullPath.lastIndexOf("\\") + 1;
                if (index === 0) {
                    index = fullPath.lastIndexOf("/") + 1;
                }
                var filename = fullPath.substr(index);

                return filename;
            };

            //validate file function
            function validateFile(fileName, filesi) {
                var validFile = true;
                //validate extension
                if (!(globalConfig.regexAllowedExtension).test(fileName)) {
                    alert('Only accepted file types: ' + globalConfig.allowedExtension);
                    validFile = false;
                }
                //validate fileSize (not support in <= IE 9)
                if (filesi > 0 && filesi > fileSize) { // 2mb
                    alert('Please upload a smaller file, max size is 0.5 MB (512kb)');
                    validFile = false;
                }
                //validate maxFiles
                if (scope.newtopic.attachments.length >= 3) {
                    alert('Max files is reached');
                    validFile = false;

                }
                return validFile;
            }

            function changeFileUploadControl(e) {
                if (typeof jQuery(e) != 'undefined') {
                    jQuery(e).removeClass("active-file");
                    jQuery(e).addClass("has-file");
                    if (typeof jQuery(e).next() != 'undefined') {
                        if (!jQuery(e).next().hasClass("has-file")) {
                            jQuery(e).next().addClass("active-file");
                        } else {
                            changeFileUploadControl(jQuery(e).next());
                        }
                    }
                }
            }

            //file change function
            function fileChange() {
                var fileName = getFileNameFromPath(jQuery(this).val());
                jQuery(this).removeClass("file-error");
                if (!validateFile(fileName, 0)) {
                    jQuery(this).addClass("file-error");
                } else {
                    scope.$broadcast('createtopicfileadded', { file: fileName });
                    changeFileUploadControl(jQuery(this));
                }
            }

            function createUploadControl() {
                //clear old file upload control
                jQuery("#file-upload-control").html('');
                //append new file upload control
                for (var i = 0; i < scope.newTopicMaxFiles; i++) {
                    jQuery("<input type='file' id='file-" + i + "' class='ie-file " + (i == 0 ? "active-file" : "") + "' name='files[]'>").appendTo(jQuery("#file-upload-control")).bind("change", fileChange);
                }
            }

            //Open Create Topic Popup
            scope.createTopic = function () {
                //Open popup
                jQuery('#createTopicBox').modal('show');

                if (jQuery("#file-upload-control input[type=file]").size() > 0) {
                    return;
                }

                //Check if browser support drag and drop file
                if (helperSrv.isIe() === 9) {
                    //add class to html
                    jQuery("html").addClass("notsupportdragdrop");
                    createUploadControl();
                } else {
                    //add dropzone
                    jQuery("#file-upload-control").append("<input type='file' name='files[]' multiple>");

                    //file upload config
                    var config = {
                        dropZone: jQuery('#createtopicform .fu-dropzone'),
                        autoUpload: false
                    };

                    //setup file upload
                    $timeout(function () {
                        formUpload = jQuery("#createtopicform").find("#file-upload-control input[type=file]").fileupload(config)
                            .bind('fileuploadadd', function (e, data) {
                                // Turn the FileList object into an Array
                                for (var i = 0; i < data.files.length; i++) {
                                    //if file is valiad
                                    if (validateFile(data.files[i].name, data.files[i].size)) {
                                        //fire 'fileadded' event
                                        scope.$broadcast('createtopicfileadded', { file: data.files[i] });
                                        filesList.push(data.files[i]);
                                    }
                                }
                            })
                            .bind('fileuploaddone', function (e, data) {
                                scope.$broadcast('topicadded', { data: data.jqXHR.responseJSON });
                            })
                            .bind('fileuploadprogressall', function () { });
                    }, 200);
                }
            };

            //Handle 'fileadded' event
            scope.$on('createtopicfileadded', function (e, parameters) {
                if (helperSrv.isIe() === 9) {
                    scope.newtopic.attachments.push({ name: parameters.file });
                }
                else {
                    scope.newtopic.attachments.push(parameters.file);
                }
            });

            //remove attactment
            scope.deleteCurrentAttachment = function (idx, event) {
                event.preventDefault();
                //remove file from reply scope
                scope.newtopic.attachments = scope.newtopic.attachments.filter(
                function (val) {
                    return val !== this.file;
                }, this);

                //remove file from fileList array
                filesList = filesList.filter(
                function (val) {
                    return val !== this.file;
                },
                this);
            };

            //Handle 'topicadded' event
            scope.$on('topicadded', function (e, parameters) {
                scope.$apply(function () {
                    //turn off submitting state
                    scope.onSubmitting = false;
                    scope.showError = false;
                    var resp = parameters.data;
                    if (resp.result) {
                        $('#createTopicBox').modal('hide');
                        filesList = [];
                        scope.createtopicform.$setPristine();
                        //create new model and reset state by copy
                        scope.newtopic = angular.copy({ /*title: '',*/ attachments: [], message: '', directTo: '' });

                        //remove file from queue
                        jQuery(element).find(".files").empty();
                    } else {
                        //show error
                        scope.hasErrorWhilePosting = true;
                        scope.errorMessage = resp.errorMessage;
                    }
                });
            });

            //Create topic
            scope.submitTopic = function (newtopic) {
                scope.onSubmitting = false;
                scope.showError = true;

                //if (workContextSrv.getCurrentUser().followerCount===0) {
                //    //show error
                //    scope.hasErrorWhilePosting = true;
                //    scope.errorMessage = "You don't have any followers.";
                //    return;
                //}
                if (scope.createtopicform.$valid && ((scope.isDirectTo && scope.newtopic.directTo.length) || (!scope.isDirectTo))) {
                    //turn on submitting state
                    scope.onSubmitting = true;
                    
                    var to = '';
                    for (var i = 0; i < newtopic.directTo.length; i++) {
                        to += newtopic.directTo[i].userName + ',';
                    }
                    //remove last comma
                    to = to.replace(/^,|,$/, '');
                    var message = newtopic.message.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, "<br/>");

                    if ((helperSrv.isIe() === 9)) {
                        //create unique id
                        var frameId = "upload_frame_" + new Date().getTime();
                        //append iframe for post
                        jQuery("#createtopicform").append('<iframe id="' + frameId + '" name="' + frameId + '" class="hidden"></iframe>');
                        //handle event when iframe loaded
                        jQuery('#' + frameId).on('load', function () {
                            //parse result to json
                            var resp = angular.fromJson(jQuery(this).contents().find('pre').html());
                            //hide indicator
                            scope.onSubmitting = false;
                            //fire 'replyadded' event
                            $timeout(function () {
                                scope.$broadcast('topicadded', { data: resp });
                                $rootScope.$broadcast('globalTopicAdded', { data: resp });
                            });
                            //remove iframe
                            jQuery(this).remove();
                            createUploadControl();
                        });
                        //get form
                        var $form = jQuery("#createtopicform");
                        //remove input file without selected file
                        $form.find("#file-upload-control input[type=file]").each(function () {
                            if (!jQuery(this).hasClass("has-file")) {
                                jQuery(this).remove();
                            }
                        });
                        
                        //add attribute to form
                        $form.attr('action', postUrl + '?from=' + username + '&to=' + to);
                        $form.attr('method', 'post');
                        $form.attr('enctype', 'multipart/form-data');
                        //change target to iframe and submit
                        $form.attr('target', frameId).submit();

                    } else {

                        topicSrv.addTopic({ from: username, to: to }, { message: message, filesList: filesList })
                            .success(function (dt) {
                                scope.onSubmitting = false;
                                $timeout(function () {
                                    //fire 'topicadded' event
                                    scope.$broadcast('topicadded', { data: dt });
                                    $rootScope.$broadcast('globalTopicAdded', { data: dt });
                                });
                            });
                    }

                }
            };

            scope.userFollowing = currentUser.follower;

            //handle model close action
            jQuery('#createTopicBox').on('hidden.bs.modal', function () {
                scope.$apply(function () {
                    filesList = [];
                    scope.onSubmitting = false;
                    scope.showError = false;
                    scope.hasErrorWhilePosting = false;
                    scope.errorMessage = '';
                    scope.isDirectTo = false;
                    scope.createtopicform.$setPristine();
                    scope.newtopic = { attachments: [], message: '', directTo: [] };
                    jQuery(element).find(".files").empty();
                    jQuery("#directtoblock").slideUp();
                });
            });
        }
    };
}])
    .directive("downloadFile", [function () {
        return {
            scope: {
                file: '='
            },
            restrict: 'E',
            replace: true,
            controller: ['$scope',function ($scope) {
                //Save file
                //$scope.onDownloading = false;
                $scope.saveFile = function (file) {
                    var oid = typeof file.documentOid === 'undefined' ? file.oid : file.documentOid;
                    //$scope.onDownloading = true;
                    window.open('api/docs/' + oid);
                    //topicSrv.downloadAttachment(file.oid).success(function (data, status) {
                    //    console.log(data);
                    //    $scope.onDownloading = false;
                    //}).error(function (dt, st) {
                    //    $scope.onDownloading = false;
                    //});
                };
            }],
            template: '<b class="pull-left col-sm-6 btnsavefile" ng-click="saveFile(file)"><i class="fa fa-file"></i> {{file.fileName}}</b>'
        };
    }])
    .directive("selectMulti", [function () {
        return {
            restrict: "A",
            require: 'ngModel',
            link: function () {
                $(function () {

                });
            }
        };
    }]);